/**
 *****************************************************************************
 * DESC ：. 
 * Author : Junwei Zhang 
 * CREATEDATE ：2012-7-4 
 * MODIFYLIST ：       	Name 			 Date 			Reason/Contents
 * 				------------------------------------------------------ 
 * 				 	Junwei Zhang     2012-7-4		Created.
 ****************************************************************************
 **/
package com.me.client;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 客户端工作线程类. <br/>
 * 上午8:50:04 2012-7-4
 * 
 * @Author <a href="mailto:mestudying@sina.com">Junwei Zhang</a><br/>
 **/
public class JTalkClientThread extends Thread {

	private JTalkClient parent = null;
	private ByteBuffer receiveBuffer = ByteBuffer.allocate(JTalkClient.BLOCK);
	private ByteBuffer sendBuffer = ByteBuffer.allocate(JTalkClient.BLOCK);
	private Selector selector = null;
	private Set<SelectionKey> keys = null;
	private SocketChannel socketChannel = null;
//	private String sendText = null;
	private List<String> messageList = null;

	// private BufferedReader in = null;
	// private String lastPackage = null;
	/** Stop the loop. */
	// private boolean stopNow = false;

	public JTalkClientThread(JTalkClient jTalkClient/* , BufferedReader in */) {
		this.parent = jTalkClient;
		this.selector = this.parent.getSelector();
		this.socketChannel = this.parent.getSocketChannel();
		// this.in = in;
		this.setName("JTalkClientThread-" + this.toString());
		this.messageList = new ArrayList<String>();
	}

	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				selector.select(10);
				keys = selector.selectedKeys();
				if(keys.size() == 2){
					System.out.println("test selected keys count--" + keys.size());
				}
				Iterator<SelectionKey> iterator = keys.iterator();
				SelectionKey key = null;
				while (iterator.hasNext()) {
					key = iterator.next();
					iterator.remove();
					if (key.isReadable()) {
						// 处理获取到的消息
						receiveBuffer.clear();
						int count = socketChannel.read(receiveBuffer);
						String s = new String(receiveBuffer.array(), 0, count);
						System.out.println("Received:" + s);
						this.parent.getMyProtocal().processServerPackage(s);
//						this.setChannelReadable();
					} else if (key.isWritable()) {
						if(messageList.size() > 0){
							String s = this.remove(0);
							sendBuffer.clear();
							sendBuffer.put(s.getBytes());
							sendBuffer.flip();
							socketChannel.write(sendBuffer);
							System.out.println("[send:]" + s);
							this.setChannelWritable();
						}else{
							this.setChannelReadable();
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Override public void run() { try { while((this.lastPackage = in.readLine()) != null &&
	 *           !"null".equals(this.lastPackage)){ System.out.println("[recv]: " + this.lastPackage); if(this.stopNow){
	 *           return; } if(!this.parent.myProtocal.processServerPackage(this.lastPackage)){
	 *           System.err.println("*** Thread: Faulty package recieved: " + this.lastPackage); } } } catch
	 *           (IOException e) { System.err.println("*** Thread: Main-loop-error: " + e.getMessage()); } }
	 */

	public void terminate() {
		// this.stopNow = true;
	}
	
	public void setChannelWritable() throws IOException{
		if(this.socketChannel != null){
			this.socketChannel.register(selector, SelectionKey.OP_WRITE);
		}
	}
	
	public void setChannelReadable() throws IOException{
		if(this.socketChannel != null){
			this.socketChannel.register(selector, SelectionKey.OP_READ);
		}
	}
	
	public boolean add(String msg){
		return this.messageList.add(msg);
	}
	
	public String remove(int index){
		return this.messageList.remove(index);
	}

}
